<template>
  <el-dialog
    v-if="visible"
    v-el-drag-dialog
    title="称重"
    :visible.sync="visible"
    width="1024px"
    @closed="resetData"
  >
    <el-form ref="dataForm" class="form" :model="temp" :rules="rules" label-position="right" label-width="130px">
      <el-form-item label="单号:">
        <el-input v-model="temp.orderCode" disabled />
      </el-form-item>
      <el-form-item label="责任机构:">
        <el-input v-model="temp.orgName" disabled />
      </el-form-item>
      <el-form-item label="批发类型:">
        <el-input v-model="wsaleType" disabled />
      </el-form-item>
      <el-form-item label="支付方式:">
        <el-input v-model="paymentMethod" disabled />
      </el-form-item>
      <el-form-item label="客户:">
        <el-input v-model="temp.csmName" disabled />
      </el-form-item>
      <el-form-item label="电话:">
        <el-input v-model="temp.contactPhone" disabled />
      </el-form-item>
      <el-form-item label="地址:" class="block">
        <el-input v-model="temp.csmAddress" disabled />
      </el-form-item>
      <el-form-item label="车辆编号:">
        <el-input v-model="temp.truckNo" disabled />
      </el-form-item>
      <el-form-item label="商品:">
        <el-input v-model="goodsName" disabled />
      </el-form-item>
      <el-form-item label="单价:">
        <el-input v-model="gPrice" disabled />
      </el-form-item>
      <el-form-item v-show="temp.wsaleType === 3" label="单价(元/吨):">
        <el-input v-model="gPrice" disabled />
      </el-form-item>
      <el-form-item label="灌装费:">
        <el-input v-model="temp.totalFee1" disabled />
      </el-form-item>
      <el-form-item v-show="temp.wsaleType === 3" label="运费单价(元/吨):" prop="freightPrice" :rules="{ required: temp.wsaleType === 3, message: '请输入运费单价', trigger: 'change' }">
        <el-input-number v-model="temp.freightPrice" :controls="false" :min="0" :max="10000" :precision="2" style="width: 100%;" @change="setTotal(1)" />
      </el-form-item>
      <el-form-item label="总运费:" prop="decimalSpare1" :rules="{ required: temp.wsaleType === 3, message: '请输入运费', trigger: 'change' }">
        <el-input-number v-model="temp.decimalSpare1" :disabled="temp.wsaleType === 3" :controls="false" :min="0" :precision="2" style="width: 100%;" @change="setTotal(1)" />
      </el-form-item>
      <el-form-item label="空车重(吨):" prop="weight1">
        <el-input-number v-model="temp.weight1" :controls="false" :min="0" :max="99999" :precision="5" style="width: 100%;" @change="setTotal(2)" />
      </el-form-item>
      <el-form-item label="实车重(吨):" prop="weight2">
        <el-input-number v-model="temp.weight2" :controls="false" :min="0" :max="99999" :precision="5" style="width: 100%;" @change="setTotal(2)" />
      </el-form-item>
      <el-form-item label="实收净重(吨):" prop="totalNetWeight">
        <el-input-number v-model="totalNetWeight" :controls="false" :min="0" :max="99999" :precision="5" style="width: 100%;" @change="setTotal(3)" />
      </el-form-item>
      <el-form-item label="盈余量(吨):" prop="weight3">
        <el-input-number v-model="temp.weight3" :controls="false" :min="-99999" :max="99999" :precision="5" style="width: 100%;" disabled />
      </el-form-item>
      <el-form-item label="" class="block">
        <el-button
          type="primary"
          @click="weighing(1)"
        ><svg-icon class="weight-icon" icon-class="weight1" />空车称重</el-button>
        <el-button
          type="primary"
          @click="weighing(2)"
        ><svg-icon class="weight-icon" icon-class="weight2" />重车称重</el-button>
      </el-form-item>

      <el-form-item label="备注:" prop="remark" class="block">
        <el-input v-model="temp.remark" type="textarea" :rows="3" maxlength="255" show-word-limit />
      </el-form-item>
    </el-form>
    <h3>应收金额：{{ totalMoney }}</h3>
    <to-pay ref="toPay" />
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="save">
        暂存
      </el-button>
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.doSave" type="primary" @click="success">
        完成称重
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { keepDotLength } from '@/utils/math'
  import ToPay from './ToPay'
  import { queryWsaleOrderBillDetail, saveLorryOrderAccount } from '@/api'

  export default {
    name: 'weighing-lorry-order',
    components: {
      ToPay
    },
    data() {
      return {
        visible: false,
        defaultData: {},
        temp: {
          gPrice: ''
        },
        totalMoney: 0,
        totalNetWeight: undefined,
        rules: {
          weight1: [{ required: false, message: '请输入空车重', trigger: 'change' }],
          weight2: [{ required: false, message: '请输入重车重', trigger: 'change' }],
          totalNetWeight: [{ required: true, message: '请输入实收净重', trigger: 'change' }]
        }
      }
    },
    computed: {
      wsaleType: function() {
        const obj = {
          1: '预约批发',
          2: '上门批发',
          3: '代运业务'
        }
        return obj[this.temp.wsaleType]
      },
      paymentMethod: function() {
        const obj = {
          0: '',
          1: '现金',
          2: '微信支付',
          16: '月结',
          128: '支付宝',
          256: '预付卡',
          512: '国志钱包',
          1024: '银行支付'
        }
        return obj[this.temp.paymentMethod]
      },
      goodsName: function() {
        return this.temp.orderWsaleOrderDetailInfoList && this.temp.orderWsaleOrderDetailInfoList.length ? this.temp.orderWsaleOrderDetailInfoList[0].goodsName : ' '
      },
      gPrice: function() {
        return this.temp.orderWsaleOrderDetailInfoList && this.temp.orderWsaleOrderDetailInfoList.length ? (this.temp.orderWsaleOrderDetailInfoList[0].gPrice).toFixed(2) : ' '
      },
      totalFee1: function() {
        return this.temp.totalFee1 ? this.temp.totalFee1.toFixed(2) : ''
      },
      weight1: function() {
        return (this.temp.weight1 / 1000).toFixed(5)
      },
      weight2: function() {
        return (this.temp.weight2 / 1000).toFixed(5)
      },
      weight3: function() {
        return this.temp.weight3 === 0 ? '0.00000' : (this.temp.weight3 / 1000).toFixed(5)
      },
      decimalSpare1: function() {
        return this.temp.decimalSpare1 === 0 ? '0.00' : this.temp.decimalSpare1.toFixed(2)
      }
    },
    methods: {
      async open(val) {
        // await Promise.all([])
        return new Promise(async resolve => {
          this.resolve = resolve
          this.visible = true
          this.defaultData = val
          this.temp.weight1 = 0
          this.temp.weight2 = 0
          this.temp.weight3 = 0
          const res = await queryWsaleOrderBillDetail({
            orderCode: val.orderCode
          })
          this.temp = res.data
          this.temp.gPrice = res.data.orderWsaleOrderDetailInfoList ? res.data.orderWsaleOrderDetailInfoList[0].gPrice : 0
          this.temp.weight1 = this.weight1
          this.temp.weight2 = this.weight2
          this.temp.weight3 = this.weight3
          this.remark = ''
          if (res.data.totalNetWeight || res.data.totalNetWeight === 0) {
            this.$set(this, 'totalNetWeight', keepDotLength(res.data.totalNetWeight / 1000, 5).toFixed(5))
          }
          if (this.temp.remark) {
            this.remark = this.temp.remark
          }
          const value1 = keepDotLength(this.temp.gPrice, 2) * keepDotLength(this.totalNetWeight, 5) + keepDotLength(this.temp.totalFee1, 2) + keepDotLength(this.temp.decimalSpare1, 2)
          this.totalMoney = value1.toFixed(2)
        })
      },
      setTotal(type) {
        switch (type) {
        case 1:
        {
          if (this.temp.wsaleType === 3) {
            this.temp.decimalSpare1 = (this.totalNetWeight * this.temp.freightPrice).toFixed(2)
          }
          const value1 = keepDotLength(this.temp.gPrice, 2) * keepDotLength(this.totalNetWeight, 5) + keepDotLength(this.temp.totalFee1, 2) + keepDotLength(this.temp.decimalSpare1, 2)
          this.totalMoney = value1.toFixed(2)
          break
        }
        case 2:
        {
          let totalNetWeight = 0
          this.temp.weight1 = this.temp.weight1 && this.temp.weight1 !== 'NaN' ? this.temp.weight1 : 0
          if (this.temp.weight1 > this.temp.weight2) {
            totalNetWeight = 0
          } else {
            totalNetWeight = (this.temp.weight2 - this.temp.weight1).toFixed(5)
          }
          this.totalNetWeight = totalNetWeight
          if (this.temp.wsaleType === 3) {
            this.temp.decimalSpare1 = (this.totalNetWeight * this.temp.freightPrice).toFixed(2)
          }
          const value2 = keepDotLength(this.temp.gPrice, 2) * keepDotLength(totalNetWeight, 5) + keepDotLength(this.temp.totalFee1, 2) + keepDotLength(this.temp.decimalSpare1, 2)
          this.totalMoney = value2.toFixed(2)
          // this.temp.weight3 = this.temp.weight2 - this.temp.weight1 - (keepDotLength(this.totalNetWeight, 5)).toFixed(5)
          break
        }
        case 3:
        {
          if (this.temp.wsaleType === 3) {
            this.temp.decimalSpare1 = (this.totalNetWeight * this.temp.freightPrice).toFixed(2)
          }
          const value3 = keepDotLength(this.temp.gPrice, 2) * keepDotLength(this.totalNetWeight, 5) + keepDotLength(this.temp.totalFee1, 2) + keepDotLength(this.temp.decimalSpare1, 2)
          this.totalMoney = value3.toFixed(2)
          this.temp.weight3 = this.temp.weight2 - this.temp.weight1 - (keepDotLength(this.totalNetWeight, 5)).toFixed(5)
          break
        }
        }
      },
      // 暂存
      async save() {
        const params = {
          corpSN: this.temp.corpSN,
          orderCode: this.temp.orderCode,
          weight1: this.temp.weight1 ? (this.temp.weight1 * 1000).toFixed(2) : '',
          weight2: this.temp.weight2 ? (this.temp.weight2 * 1000).toFixed(2) : '',
          weight3: (this.temp.weight3 * 1000).toFixed(2),
          totalNetWeight: (this.totalNetWeight * 1000).toFixed(2),
          remark: this.temp.remark
        }
        console.log(params)
        const res = await saveLorryOrderAccount(params)
        if (res && res.data) {
          this.$message.success('暂存成功')
          this.visible = false
          this.resolve()
        }
      },
      // 完成称重
      async success() {
        this.$refs.dataForm.validate(async valid => {
          if (!valid) return
          // 校验空车重
          if (keepDotLength(this.temp.weight1 * 1000, 2) === 0) {
            this.$message.error('请输入空车重')
            return
          }
          // 校验重车重
          if (keepDotLength(this.temp.weight2 * 1000, 2) === 0) {
            this.$message.error('请输入重车重')
            return
          }
          // 校验空车重 与重车重
          if (keepDotLength(this.temp.weight1 * 1000, 2) === keepDotLength(this.temp.weight2 * 1000, 2)) {
            this.$message.error('实收净重数据异常')
            return
          }
          // 校验空车重 与重车重
          if (keepDotLength(this.temp.weight1 * 1000, 2) > keepDotLength(this.temp.weight2 * 1000, 2)) {
            this.$message.error('输入的空车重大于重车重,不可提交')
            return
          }
          this.$confirm('确认完成称重？', '提示', {
            type: 'warning'
          }).then(() => {
            this.doSave()
          })
        })
      },
      async doSave() {
        // const tReceivable = accMul(keepDotLength(this.temp.gPrice, 2), keepDotLength(this.totalNetWeight, 5))
        const params = {
          totalNetWeight: (this.totalNetWeight * 1000).toFixed(2),
          orderCode: this.temp.orderCode,
          weight3: (this.temp.weight3 * 1000).toFixed(2),
          tReceivables: this.totalMoney, // 总金额
          remark: this.temp.remark,
          weight1: (this.temp.weight1 * 1000).toFixed(2),
          weight2: (this.temp.weight2 * 1000).toFixed(2),
          orderStatus: 2,
          decimalSpare1: this.temp.decimalSpare1
        }
        if (this.temp.wsaleType === 3) {
          params.freightPrice = this.temp.freightPrice
        }
        const res = await saveLorryOrderAccount(params)
        if (res && res.data) {
          this.$message.success('操作成功')
          this.visible = false
          this.resolve()
        }
      },
      weighing(type) {
        console.log(window)
        const ws = window.jCPrint
        const json = { cmd: 20 }
        ws.send(JSON.stringify(json))
        ws.registListener((msg) => {
          console.log(msg, '-----')
          this.handleMsg(type, msg)
        })
      },
      handleMsg(type, msg) {
        const msgObj = msg ? JSON.parse(msg) : ''
        if (msgObj && msgObj.data && !(msgObj.auto)) {
          if (msgObj.data === '空') {
            this.$message.error('数据为空！')
          } else {
            console.log(msgObj.data)
            // const msgList = msgObj.data.split(' ')
            // const wList = msgList.map((item) => (item ? item.substring(0, 1) : '')).slice(5, 9)
            // const wStr = wList.join('')
            // if (wStr) {
            //   if (type === 1) {
            //     this.temp.weight1 = Number(wStr)
            //     if (this.temp.weight2) this.setTotal(2)
            //   }
            //   if (type === 2) {
            //     this.temp.weight2 = Number(wStr)
            //     if (this.temp.weight1) this.setTotal(2)
            //   }
            //   console.log(this.temp, Number(wStr))
            // }
            const ret = msgObj.data.slice(15, 29)
            if (ret) {
              const msgList = ret.split(' ')
              const wStr = msgList[0].slice(0, 1) + msgList[1].slice(0, 1) + msgList[2].slice(0, 1) + msgList[3].slice(0, 1) + msgList[4].slice(0, 1)
              if (wStr) {
                if (type === 1) {
                  this.temp.weight1 = (Number(wStr) / 1000).toFixed(5)
                  if (this.temp.weight2) this.setTotal(2)
                }
                if (type === 2) {
                  this.temp.weight2 = (Number(wStr) / 1000).toFixed(5)
                  if (this.temp.weight1) this.setTotal(2)
                }
                console.log(this.temp, Number(wStr))
              } else {
                this.$message.error('获取数据失败')
              }
            }
          }
        }
      },
      // 重置数据
      clearData() {
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      },
      resetData() {
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 33.3%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
.weight-icon {
  margin-right: 10px;
}
</style>
